<?php
/**
 * Search statistics 
 */
class SearchStatistics extends Zend_Db_Table
{
	/**
	 * Table name
	 *  
	 * @var string
	 */
	protected $_name = 'search_statistics';
	
	/**
	 * Database primary key 
	 * 
	 * @var string
	 */
	protected $_id = 'id';
	
	/**
	 * Save search statistics information 
	 * 
	 * @param	string $searchPhrase
	 * @param	int $source_id
	 * @param	int $translation_id
	 * @return void
	 */
	public function saveStats($searchPhrase, $sourceId, $translationId)
	{
		/**
		 * Get this value from super global variable,
		 * this can be improved in advance
		 * 
		 * @var stirng
		 */
		$UserIP = $_SERVER['REMOTE_ADDR'];
		
		$searchInfo = array(
		      'search_phrase'	=> $searchPhrase
			, 'source_lang_id'	=> $sourceId
			, 'target_lang_id'	=> $translationId
			, 'visitor_ip'		=> $UserIP
		);
		
		$this->insert($searchInfo);
	}
	
	/**
	 * Returns popular searches to generate tags cloud
	 *  
	 * @return Zend_Db_Rowset
	 */
	public function getPopularSearches()
	{
		// get source and target language Ids
		$User = Wise_User_Session::getInstance();
		
		$sourceLangId = $User->source_lang;
		$targetLangId = $User->target_lang;
		
		$db = $this->getAdapter();

		/**
		 * @var Zend_Db_Select
		 */
		$select = $db->select()
			->from(array('ss' => 'search_statistics'), 
			array(
				  'phrase'	=> 'ss.search_phrase'
				, 'num'		=> new Zend_Db_Expr('COUNT(ss.`search_phrase`)'))
			);
			
			if ($sourceLangId) {
				$select->where('ss.source_lang_id = ?', $sourceLangId);
			}
			
			if ($targetLangId) {
				$select->where('ss.target_lang_id = ?', $targetLangId);
			}
			
			$select->group('ss.search_phrase')
			->order(new Zend_Db_Expr('COUNT(ss.`search_phrase`)') . ' DESC')
			->limit(40);
		
		return $db->fetchAll($select);
	}
}